package com.woniu.controller;

import com.alibaba.fastjson.JSON;
import com.woniu.entity.Product;
import com.woniu.service.IProductService;
import com.woniu.vo.Constants;
import com.woniu.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@Slf4j
public class ProductController {

    @Autowired
    private IProductService productService;

    @GetMapping("/products/{pid}")
    public ResultVO find(@PathVariable("pid") Integer pid) {
        log.info("即将查询: {} 商品", pid);
        Product product = productService.findByPid(pid);

        ResultVO resultVO = null;
        if(product != null) {
            log.info("已查到：{} 商品，内容：{}", pid, JSON.toJSONString(product));
            resultVO = new ResultVO(Constants.OPER_SUCCESS, "查询成功", product);
        } else {
            log.info("未查到：{} 商品", pid);
            resultVO = new ResultVO(Constants.OPER_FAILURE, "查询失败");
        }

        return resultVO ;
    }

    @GetMapping("/products/testloadbalance")
    public ResultVO testLoadBalance(HttpServletRequest request) {
        return new ResultVO(Constants.OPER_SUCCESS, "处理本次请求的product-service实例端口：" + request.getServerPort());
    }
}